﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web;

namespace Mindfor.Web.Routing
{
	/// <summary>
	/// Defines contract that matches only GUID.
	/// </summary>
	public class GuidConstraint : IRouteConstraint
	{
		/// <summary>
		/// Determines whether the URL parameter contains a valid value for this constraint.
		/// </summary>
		/// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
		/// <param name="route">The object that this constraint belongs to.</param>
		/// <param name="parameterName">The name of the parameter that is being checked.</param>
		/// <param name="values">An object that contains the parameters for the URL.</param>
		/// <param name="routeDirection">An object that indicates whether the constraint check is being performed when an incoming request is being handled or when a URL is being generated.</param>
		/// <returns>true if the URL parameter contains a valid value; otherwise, false.</returns>
		public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
		{
			if (values.ContainsKey(parameterName))
			{
				object val = values[parameterName];
				if (val != null)
				{
					if (val is Guid)
						return true;
					else
					{
						string stringValue = val.ToString();
						if (!String.IsNullOrEmpty(stringValue))
						{
							Guid guidValue;
							return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty);
						}
					}
				}
			}
			return false;
		}
	}
}
